﻿using System;

namespace Codemonk.Common.Configuring
{
    public abstract class Configurable : IConfigurable
    {
        private IConfigReader reader;
        public virtual IConfigReader Reader
        {
            set
            {
                if (value == reader) return;
                if (reader != null)
                {
                    reader.EnableMonitoring = false;
                    reader.OnFileChanged -= reader_OnFileChanged;
                }
                reader = value;
                if (value != null && value.EnableMonitoring)
                    reader.OnFileChanged += reader_OnFileChanged;
            }
            get { return reader; }
        }

        private void reader_OnFileChanged(object sender, EventArgs e)
        {
            //使用后台线程重新读取配置文件
            System.Threading.ThreadPool.QueueUserWorkItem(backgroundInitailzaton);
        }

        private void backgroundInitailzaton(object state)
        {
            try
            {
                Initialization();
            }
            catch { }
        }

        public abstract void Initialization();
    }
}
